#!/usr/bin/env python3
import sys
import json
import subprocess
import os

# 测试脚本：用于验证原生主机程序是否正常工作
def main():
    # 获取原生主机程序路径
    current_dir = os.path.dirname(os.path.abspath(__file__))
    host_path = os.path.join(current_dir, "output/TopMostHost")
    
    print(f"测试原生主机程序: {host_path}")
    print("="*50)
    
    # 测试命令列表
    test_commands = [
        {"command": "setup", "extension_id": "dkdeinpkanckjmaeknpkidhpaocaceje"},
        {"command": "query"},
        {"command": "set"},
        {"command": "toggle"},
        {"command": "unset"}
    ]
    
    # 逐个测试命令
    for cmd in test_commands:
        print(f"\n测试命令: {cmd['command']}")
        try:
            # 启动原生主机程序
            process = subprocess.Popen(
                [host_path],
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            
            # 准备消息
            message = json.dumps(cmd).encode('utf-8')
            length = len(message).to_bytes(4, byteorder='little')
            
            # 发送消息
            process.stdin.write(length)
            process.stdin.write(message)
            process.stdin.flush()
            
            # 读取响应
            response_length_bytes = process.stdout.read(4)
            if len(response_length_bytes) != 4:
                print(f"  错误: 未收到正确的响应长度前缀")
                continue
            
            response_length = int.from_bytes(response_length_bytes, byteorder='little')
            response_data = process.stdout.read(response_length)
            response = json.loads(response_data.decode('utf-8'))
            
            print(f"  响应: {response}")
            if response.get('ok', False):
                print(f"  结果: 成功")
            else:
                print(f"  结果: 失败")
                
        except Exception as e:
            print(f"  错误: {str(e)}")
    
    print("\n" + "="*50)
    print("测试完成。请在Chrome中重新加载扩展并测试功能。")
    print("如果扩展无法工作，请检查manifest.json文件中的扩展ID是否与实际一致。")

if __name__ == "__main__":
    main()
